package com.lxj.cms.manage.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.Criteria;

import com.lxj.core.action.BaseAction;
import com.lxj.core.entity.SYSBaseEntity;

@SuppressWarnings("serial")
@ParentPackage("amdin_manager_Interceptor")
@Namespace(value = "/manage/admin")
@InterceptorRefs( { @InterceptorRef("loginStack") })
public class ManageBaseAction extends BaseAction {

	public static JsonConfig config = new JsonConfig();

	static {
		config.setIgnoreDefaultExcludes(false);
		config.registerJsonValueProcessor(Long.class, new LongValueProcessor());
		config.registerJsonValueProcessor(int.class, new LongValueProcessor());
		config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		config.registerJsonValueProcessor(Timestamp.class, new TimestampDateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		// 只要设置这个数组，指定过滤哪些字段。
		config.setExcludes(new String[] { "beanState", "remark" });
	}

	private Long optionId;

	private int rows;// 每页显示的记录数
	private int page;// 当前第几页

	public void setResult(Map<Object, Object> map) {
		String jsonString = JSONSerializer.toJSON(map, config).toString();
		wirteResponse(jsonString);
	}

	public void setResult(Map<Object, Object> map, String[] excludes) {
		config.setExcludes(excludes);
		String jsonString = JSONSerializer.toJSON(map, config).toString();
		wirteResponse(jsonString);
	}

	public void wirteResponse(String content) {
		HttpServletResponse resp = ServletActionContext.getResponse();
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");
		PrintWriter out = null;
		try {
			out = resp.getWriter();
			out.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	public void setResult(SYSBaseEntity entity) {
		String jsonString = JSONSerializer.toJSON(entity, config).toString();
		wirteResponse(jsonString);
	}

	public Criteria getResultCriteria(Criteria criteria) {
		// 当前页
		int intPage = page == 0 ? 1 : page;
		// 每页显示条数
		int number = rows == 0 ? 10 : rows;
		// 每页的开始记录 第一页为1 第二页为number +1
		int start = (intPage - 1) * number;
		int total = criteria.list().size();
		criteria.setFirstResult(start);
		criteria.setMaxResults(number);
		return criteria;
	}

	public void responseJson(int total, List<Map<String, Object>> mapList) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("total", total);// total键 存放总记录数，必须的
		jsonMap.put("rows", mapList);// rows键 存放每页记录 list
		String jsonString = JSONSerializer.toJSON(jsonMap, config).toString();
		wirteResponse(jsonString);
	}

	public void setResult(Criteria criteria, String[] excludes) {
		config.setExcludes(excludes);
		setResult(criteria);
	}

	public void setResult(Criteria criteria) {
		// 当前页
		int intPage = page == 0 ? 1 : page;
		// 每页显示条数
		int number = rows == 0 ? 10 : rows;
		// 每页的开始记录 第一页为1 第二页为number +1
		int start = (intPage - 1) * number;
		int total = criteria.list().size();

		criteria.setFirstResult(start);
		criteria.setMaxResults(number);

		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("total", total);// total键 存放总记录数，必须的
		jsonMap.put("rows", criteria.list());// rows键 存放每页记录 list

		String jsonString = JSONSerializer.toJSON(jsonMap, config).toString();

		wirteResponse(jsonString);
	}

	public Long getOptionId() {
		return optionId;
	}

	public void setOptionId(Long optionId) {
		this.optionId = optionId;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

}

class LongValueProcessor implements JsonValueProcessor {

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	private Object process(Object value) {

		return value.toString();
	}
}

class DateJsonValueProcessor implements JsonValueProcessor {
	private String format = "yyyy-MM-dd";

	public DateJsonValueProcessor() {
	}

	public DateJsonValueProcessor(String format) {
		this.format = format;
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		String[] obj = {};
		if (value instanceof Date[]) {
			SimpleDateFormat sf = new SimpleDateFormat(format);
			Date[] dates = (Date[]) value;
			obj = new String[dates.length];
			for (int i = 0; i < dates.length; i++) {
				obj[i] = sf.format(dates[i]);
			}
		}
		return obj;
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value.toString();
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

}

/**
 * 将Bean中的Timestamp转换为json中的日期字符串
 */
class TimestampDateJsonValueProcessor implements JsonValueProcessor {
	public static final String Default_DATE_PATTERN = "yyyy-MM-dd";
	private DateFormat dateFormat;

	public TimestampDateJsonValueProcessor(String datePattern) {
		try {
			dateFormat = new SimpleDateFormat(datePattern);

		} catch (Exception e) {
			dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);

		}

	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	private Object process(Object value) {
		return dateFormat.format((Date) value);

	}
}
